package com.ttc.mBackup.BackupImages;

import java.io.File;
import java.util.ArrayList;

import com.ttc.mBackup.R;
import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;

import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class RestoreImageActivity extends Activity {

	@Override
	protected void onDestroy() {
		FileManager.deleteTempFile();
		System.gc();
		super.onDestroy();
	}
	
	private TextView txtBackupDate;
	private TextView txtBackupDescriptions;
	private Button btnNext;
	private ListView listView;
	ArrayList<String> listBackupFile;
	File[] backupFiles;
	
	private CustomListAdapter adapter;
	private int selectedIndex;
	String[] content;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.i_layout_restore_image);
		
		
		
		btnNext = (Button)findViewById(R.id.i_restore_btnNext);
		txtBackupDate = (TextView) findViewById(R.id.i_restore_txtDate);
		txtBackupDescriptions = (TextView) findViewById(R.id.i_restore_txtDescription);
		
		listView = (ListView) findViewById(R.id.i_layout_restore_image_list);
		listBackupFile = new ArrayList<String>();
		backupFiles = FileManager.getBackupFiles();
		
		if(backupFiles!=null && backupFiles.length!= 0){
			for (File f : backupFiles) {
				listBackupFile.add(f.getName());
			}
			
		}
		
		adapter = new CustomListAdapter(listBackupFile, getApplicationContext());
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(onItemClick);
		
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), RunRestoreActivity.class);
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("BACKUFILE", backupFiles[selectedIndex]);
				bundle.putSerializable("CONTENTS", content);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}
	
	OnItemClickListener onItemClick = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			selectedIndex = position;
			adapter.setSelectedIndex(position);
			adapter.notifyDataSetChanged();
			
			String backupFilePath = backupFiles[position].getPath();
			content = FileManager.getInfoFileFromZip(backupFilePath);
			if(content!=null){
				txtBackupDate.setText("Date: "+ content[0]);
				String des=content[1];
				if(des.length() > 15 )
					des = des.substring(0, 15) + "...";
				txtBackupDescriptions.setText("Descriptions: " + des);
			}

		}
	};

	
}
